package com.linln.agent.ad;

import java.math.BigDecimal;
import java.util.List;

import javax.servlet.http.HttpServletRequest;

import com.linln.common.utils.DateUtils;
import com.linln.modules.system.domain.Area;
import com.linln.modules.system.service.AreaService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Example;
import org.springframework.data.domain.ExampleMatcher;
import org.springframework.data.domain.Page;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.github.binarywang.wxpay.bean.request.WxPayRefundRequest;
import com.github.binarywang.wxpay.bean.result.WxPayRefundResult;
import com.github.binarywang.wxpay.exception.WxPayException;
import com.github.binarywang.wxpay.service.WxPayService;
import com.linln.common.constant.AdminConst;
import com.linln.common.constant.NoticeTypeConst;
import com.linln.common.constant.UrlConst;
import com.linln.common.utils.MoneyUtils;
import com.linln.common.utils.ResultVoUtil;
import com.linln.common.utils.ToolUtil;
import com.linln.common.vo.ResultVo;
import com.linln.modules.ad.domain.AdInfo;
import com.linln.modules.ad.service.AdInfoService;
import com.linln.modules.member.domain.MemberAgent;
import com.linln.modules.member.domain.MemberInfo;
import com.linln.modules.member.domain.MemberRefund;
import com.linln.modules.member.service.MemberAgentService;
import com.linln.modules.member.service.MemberInfoService;
import com.linln.modules.member.service.MemberOrderService;
import com.linln.modules.member.service.MemberRefundService;

/**
 * @author hct
 * @date 2019/09/12
 */
@Controller
@RequestMapping("agent/ad")
public class AgentAdController {

    @Autowired
    private AdInfoService adinfoService;
    @Autowired
    private MemberAgentService agentService;
    @Autowired
    private MemberInfoService memberService;
    @Autowired
    private AreaService areaService;

    @Autowired
    private WxPayService wxPayService;
    @Autowired
    private MemberRefundService refundService;
    

    @Autowired
    private MemberOrderService orderService;
    
    private static final String REFUND_SUCCESS = "SUCCESS";

    /**
     * 所有商户列表页面
     */
    @GetMapping("/index")
    public String index(Model model, AdInfo baseinfo,HttpServletRequest request) {

        // 创建匹配器，进行动态查询匹配
        ExampleMatcher matcher = ExampleMatcher.matching();
        baseinfo.setAdStatus(1);
       // baseinfo.setPayStatus(1);
       // MemberInfo agent=(MemberInfo)request.getSession().getAttribute(AdminConst.AGENT_ROLE_NAME);
        MemberAgent agent=(MemberAgent)request.getSession().getAttribute(AdminConst.AGENT_AREA_NAME); 
        
        baseinfo.setArea(agent.getArea());        
        // 获取数据列表
        Example<AdInfo> example = Example.of(baseinfo, matcher);
        Page<AdInfo> list = adinfoService.getPageList(example);
        List<AdInfo> content = list.getContent();
        for (AdInfo adInfo :content
             ) {
            if(adInfo==null) continue;
            Area area = areaService.findByCode(adInfo.getArea());
            if(area != null){
                Area parea = areaService.getById(area.getPid());
                adInfo.setAreaname(area.getName());
                if(parea != null){
                    adInfo.setAreaname(parea.getName()+area.getName());
                }
            }
        }
        // 封装数据
        model.addAttribute("list", content);
        model.addAttribute("page", list);
        return "/agent/ad/index";
    }
    
  
    
    /**
     * 待审核列表页面
     */
    @GetMapping("/shenheindex")
    public String shenheindex(Model model, AdInfo baseinfo,HttpServletRequest request) {

    	// 创建匹配器，进行动态查询匹配
        ExampleMatcher matcher = ExampleMatcher.matching();
        baseinfo.setAdStatus(0);
        //baseinfo.setPayStatus(1);
        MemberAgent agent=(MemberAgent)request.getSession().getAttribute(AdminConst.AGENT_AREA_NAME); 
        
        baseinfo.setArea(agent.getArea());        
        // 获取数据列表
        Example<AdInfo> example = Example.of(baseinfo, matcher);
        Page<AdInfo> list = adinfoService.getPageList(example);
        // 封装数据
        model.addAttribute("list", list.getContent());
        model.addAttribute("page", list);
        return "/agent/ad/shenheindex";
    }
    /**
     * 跳转到编辑页面
     */
    @GetMapping("/toshenhe/{id}")
     public String toEdit(@PathVariable("id") AdInfo baseinfo, Model model) {
        model.addAttribute("baseinfo", baseinfo);
        return "/agent/ad/toshenhe";
    }
    
 /*   *//**
     * 审核
     * @param model
     * @param id
     * @param storestatus  0待审核 1同意 2拒绝
     * @param request
     * @return
     *//*
    @PostMapping("/shenheAd")
    @ResponseBody
    public ResultVo save(Long id ,Integer adStatus,HttpServletRequest request) {
        // 复制保留无需修改的数据
    	AdInfo ad=adinfoService.getById(id);
    	//MemberInfo agent=(MemberInfo)request.getSession().getAttribute(AdminConst.AGENT_ROLE_NAME);
    	MemberAgent agent=(MemberAgent)request.getSession().getAttribute(AdminConst.AGENT_AREA_NAME); 
         
    	if(adinfoService.updateAdStatus(adStatus, id)) {
            if(adStatus.intValue()==1) {
            	//同意的时候将钱增加到代理商的余额中
            	MemberAgent agentnew=agentService.getById(agent.getId());
            	//代理商拿一个比例的折扣，其他的归属公司
            	Double curagentmoney=MoneyUtils.mul(ad.getFee(),0.9);
            	agentnew.setAllmoney(MoneyUtils.add(agentnew.getAllmoney(), curagentmoney));
            	agentnew.setCurmoney(MoneyUtils.add(agentnew.getCurmoney(),curagentmoney));
            	agentService.save(agentnew);
            	MemberInfo memberinfo=agent.getMember();
            	memberinfo.setAllmoney(MoneyUtils.add(memberinfo.getAllmoney(), curagentmoney));
            	memberinfo.setMoney(MoneyUtils.add(memberinfo.getMoney(), curagentmoney));
            	memberService.save(memberinfo);
            }else if(adStatus.intValue()==2) {
            	
            	if(ad.getFee().doubleValue()>0) {
            		//拒绝的时候将费用退回给客户
               	 //申请退款
                   WxPayRefundRequest refundInfo = WxPayRefundRequest.newBuilder()
                           //订单号
                           .outTradeNo(ad.getOrderId())
                           //退款订单号
                           .outRefundNo(ToolUtil.getRandomString(16)) 
                           //金额
                           .totalFee(yuanToFee(new BigDecimal(ad.getFee())))
                           //退款金额
                           .refundFee(yuanToFee(new BigDecimal(ad.getFee())))
                           //todo 回调地址
                           .notifyUrl(UrlConst.REFUNDNOTICEURL)
                           .build();
                   WxPayRefundResult wxPayRefundResult;
                   try {
                       wxPayRefundResult = wxPayService.refund(refundInfo);
                       //判断退款信息是否正确
                       if (REFUND_SUCCESS.equals(wxPayRefundResult.getReturnCode())
                               && REFUND_SUCCESS.equals(wxPayRefundResult.getResultCode())) {
                    	   saveRefund(ad,agent.getId());
                    	   
                        }
                   } catch (WxPayException e) {
                   	return ResultVoUtil.error("异常");
                   }	
            	}else {
             	   saveRefund(ad,agent.getId());
            	}
            	
            }
    		return ResultVoUtil.success("审核成功");
        	}else {
        		//
        		return ResultVoUtil.error("审核失败");
        	}
     }
    
    */
    
    public void saveRefund(AdInfo ad,Long agentId) {
    	MemberRefund refund=new MemberRefund();
       	refund.setAgentId(agentId);
       	refund.setArea(ad.getArea());
       	refund.setContent("拒绝用户投放的广告");
       	refund.setMoney(ad.getFee());
       	refund.setOrderCode(ad.getOrderId());
       	refund.setRefundmoney(ad.getFee());
       	refund.setRefundStatus(0);
       	refund.setType(NoticeTypeConst.AD);
       	refund.setTypeId(ad.getId());
       	refundService.save(refund);
    }
    
    /**
     * 审核
     * @param model
     * @param id
     * @param storestatus  0待审核 1同意 2拒绝
     * @param request
     * @return
     */
    @RequestMapping("/refundAd")
    @ResponseBody
    public ResultVo refundAd(Long id,HttpServletRequest request) {
        // 复制保留无需修改的数据
    	AdInfo ad=adinfoService.getById(id);
    	//MemberInfo agent=(MemberInfo)request.getSession().getAttribute(AdminConst.AGENT_ROLE_NAME);
    	MemberAgent agent=(MemberAgent)request.getSession().getAttribute(AdminConst.AGENT_AREA_NAME); 
         
    	if(adinfoService.updateAdStatus(2, id)) {

            	if(ad.getFee().doubleValue()>0) {
            		//拒绝的时候将费用退回给客户
               	 //申请退款
                   WxPayRefundRequest refundInfo = WxPayRefundRequest.newBuilder()
                           //订单号
                           .outTradeNo(ad.getOrderId())
                           //退款订单号
                           .outRefundNo(ToolUtil.getRandomString(16)) 
                           //金额
                           .totalFee(yuanToFee(new BigDecimal(ad.getFee())))
                           //退款金额
                           .refundFee(yuanToFee(new BigDecimal(ad.getFee())))
                           //todo 回调地址
                           .notifyUrl(UrlConst.REFUNDNOTICEURL)
                           .build();
                   WxPayRefundResult wxPayRefundResult;
                   try {
                       wxPayRefundResult = wxPayService.refund(refundInfo);
                       //判断退款信息是否正确
                       if (REFUND_SUCCESS.equals(wxPayRefundResult.getReturnCode())
                               && REFUND_SUCCESS.equals(wxPayRefundResult.getResultCode())) {
                    	   saveRefund(ad,agent.getId());
                    	   MemberAgent agentnew=agentService.getById(agent.getId());
                           agentnew.setAllmoney(MoneyUtils.sub(agentnew.getAllmoney(), ad.getFee()));
                       	   agentnew.setCurmoney(MoneyUtils.sub(agentnew.getCurmoney(),ad.getFee()));
                       	   agentService.save(agentnew);
                 		   orderService.updateRefundStatus(ad.getOrderId());

                        }
                   } catch (WxPayException e) {
                   	return ResultVoUtil.error("异常");
                   }	
            	}else {
             	   saveRefund(ad,agent.getId());
            	}
            	
             return ResultVoUtil.success("审核成功");
        	}else {
        		//
        		return ResultVoUtil.error("审核失败");
        	}
     }
    
    /**
     * 跳转到详细页面
     */
    @GetMapping("/detail/{id}")
    public String toDetail(@PathVariable("id") AdInfo baseinfo, Model model) {
        model.addAttribute("baseinfo",baseinfo);
        return "/agent/ad/detail";
    }

    /**
     * 编辑查看
     * @return
     */
    @GetMapping("/detailByEdit/{id}")
    public String detailByEdit(@PathVariable("id") AdInfo baseinfo, Model model){
        model.addAttribute("baseinfo",baseinfo);
        return "/agent/ad/edit";
    }


    /**
     * 编辑
     */
    @PostMapping("/editAdInfo")
    @ResponseBody
    public ResultVo editAdInfo(Long id,String startTime,String endTime,String pushPhone,String details,Integer readnum,String logo, String nineImgs){
        AdInfo ad = adinfoService.getById(id);
        ad.setId(id);
        ad.setPushPhone(pushPhone);
        ad.setDetails(details);
        ad.setReadnum(readnum);
        ad.setImg(logo);
        ad.setStartTime(DateUtils.strToDate(startTime,"yyyy-MM-dd hh:mm:ss"));
        ad.setEndTime(DateUtils.strToDate(endTime,"yyyy-MM-dd hh:mm:ss"));
        ad.setDetailimg(nineImgs);
        adinfoService.save(ad);
        ResultVo success = ResultVoUtil.success("修改成功");
        return success;
    }

    /**
     * 1 块钱转为 100 分
     * 元转分
     *
     * @param bigDecimal 钱数目
     * @return 分
     */
    private int yuanToFee(BigDecimal bigDecimal) {
        return bigDecimal.multiply(new BigDecimal(100)).intValue();
    }

    /**
     * 时间
     *
     * @return 时间戳
     */
    private String createTimestamp() {
        return Long.toString(System.currentTimeMillis() / 1000);
    }
}